"use strict";

$(() => {
    function replace_to_loading(el)
    {
        el = $(el);
        var loading = $('<span>', { 'class': 'fa fa-cog fa-spin' });
        el.replaceWith(loading);
        var resume = () => loading.replaceWith(el);
        return resume;
    }

    function api(url, args)
    {
        if (args instanceof HTMLFormElement) args = new FormData(args);
        var process_data = !(args instanceof FormData);
        var content_type = process_data ? undefined : false;

        var result = $.Deferred();
        $.post({
            url,
            data: args,
            processData: process_data,
            contentType: content_type,
            cache: false,
        })
            .fail(() => result.reject("连接到服务器失败"))
            .done(data => {
                if (data.error === 'login' || data.error === 'denied')
                    return reload("?throw=" + data.error)();
                if (data.error != null) return result.reject(data.error);
                result.resolve(data.result);
            });
        return result;
    }

    function button_api(ev, url, show_err)
    {
        ev.preventDefault();
        if (show_err == null) show_err = err => alert(err);

        var target = ev.currentTarget;
        var resume = replace_to_loading(target);
        var args = $(target).data();
        console.log(args);
        return api(url, args).fail(err => {
            show_err(err);
            resume();
        });
    }

    function form_api(form)
    {
        form = $(form);
        var url = form.attr('action');
        var error = $('.form-controls > .form-error', form);
        var submit = $('.form-controls > button:last-child', form);
        var resume = replace_to_loading(submit);
        var redirect = form.data('redirect');

        return api(url, form[0])
            .fail(err => {
                error.text(err);
                resume();
            })
            .done(data => redirect == null
                ? reload()()
                : goto(redirect)());
    }

    function reload(search)
    {
        if (search === null) return () => location.reload();
        if (search === undefined) search = "";
        return goto(location.pathname + search);
    }

    function goto(path)
    {
        return () => {
            location.href = path;
            if (location.pathname + location.search + location.hash === path)
                location.reload();
        }
    }

    $(document).on('click', '.logout', ev => {
        button_api(ev, '/api/auth/logout').done(reload());
    });

    $(document).on('click', '.delete-post', ev => {
        button_api(ev, '/api/post/delete').done(goto("/"));
    });

    $(document).on('click', '.delete-comment', ev => {
        button_api(ev, '/api/comment/delete').done(reload(null));
    });

    $(document).on('submit', 'form', ev => {
        ev.preventDefault();
        var form = ev.currentTarget;
        form_api(form);
    });

    $(document).on('click', '.go-back', ev => {
        ev.preventDefault();
        if (location.search.search(/\?throw=/) === 0)
            return reload()();
        var el = $(ev.currentTarget);
        location.href = el.attr('href');
    });

    // focus on first input of a form, if there is one
    $('.content-wrapper > form > *:first-child').focus();
});

